package com.nrg.richie.server;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.w3c.dom.Document;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.nrg.richie.server.utils.StringUtils;
import com.nrg.richie.server.utils.XMLUtils;

@SuppressWarnings("serial")
public class ReadServlet extends HttpServlet {

	public static final String XML_DOCUMENT = "xmlDocument";
	public static final String NODE_DATA_LIST = "NodeDataList";
	public static final String XML_DOCUMENT_FILTERED = "xmlDocumentFiltered";
	Logger logger = Logger.getLogger(ReadServlet.class.getName());
	
    public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException {

    	String fileUrl = request.getParameter("url");
    	String userName = request.getParameter("userName");
    	String password = request.getParameter("password");


//    	String fileUrl = "http://export.dh.hu/toplak/miskolc_iroda_toplak.xml";
//    	String userName = "toplak";
//    	String password = "e371e2149e";

    	
    	
    	
        Document document = null;

    	
    	if (fileUrl != null && fileUrl.trim().length() > 0
				&& userName != null && userName.trim().length() > 0
				&& password != null && password.trim().length() > 0) {
    	
	        
	        try {

	        	URL fetchurl = new URL(fileUrl);

	        	String nameAndPassword = userName+":"+password;
	        	String authorizationString = "Basic " + Base64.encode(nameAndPassword.getBytes());

	        	HTTPRequest req = new HTTPRequest(fetchurl);
	        	req.addHeader(new HTTPHeader("Authorization", authorizationString));

	        	HTTPResponse resp = URLFetchServiceFactory.getURLFetchService().fetch(req);
	        	
	        	ByteArrayInputStream in = new ByteArrayInputStream(resp.getContent());
	        	
	        	document = XMLUtils.getXml(in);
	
	        }
	        catch(Exception e){
	        	logger.severe(StringUtils.getStacktraceAsString(e));            
	        }
        
    	}
        
        if (document != null) {

        	HttpSession session = request.getSession();

        	session.setAttribute(XML_DOCUMENT, XMLUtils.getXmlString(document));
        	session.setAttribute(NODE_DATA_LIST, XMLUtils.processXml(document, request.getLocale()));

        } else {
        	PrintWriter out;
			try {
				out = response.getWriter();
	    	    response.setContentType("text/plain");
	    	    out.print("<h1>Hibas beolvasott file.</h1>");
	    	    out.close();
			} catch (IOException e) {
				logger.severe(StringUtils.getStacktraceAsString(e));
			}

        }
        
    }
}